package com.bw.wxy.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bw.wxy.R;
import com.bw.wxy.action.BroadAction;
import com.bw.wxy.common.Api;
import com.bw.wxy.common.SpUtils;
import com.bw.wxy.db.UserManager;
import com.bw.wxy.factroy.HttpCode;
import com.bw.wxy.mvp.model.entity.BaseEntity;
import com.bw.wxy.mvp.model.entity.ResponseUserEntity;
import com.bw.wxy.mvp.model.entity.UserEntity;
import com.bw.wxy.mvp.model.entity.UserItemEntity;
import com.bw.wxy.mvp.model.entity.UserMenuEntity;
import com.bw.wxy.mvp.base.view.BaseFragment;
import com.bw.wxy.mvp.contract.UserContract;
import com.bw.wxy.mvp.di.DaggerUserComponent;
import com.bw.wxy.mvp.di.UserModules;
import com.bw.wxy.mvp.presenter.UserPresenter;
import com.bw.wxy.mvp.view.DetailActivity;
import com.bw.wxy.mvp.view.LoginActivity;
import com.bw.wxy.mvp.view.LogoutActivity;
import com.bw.wxy.mvp.view.user.adapter.UserAdapter;
import com.bw.wxy.mvp.view.user.adapter.UserMenuAdapter;
import com.bw.wxy.widget.PartingLine;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import static com.blankj.utilcode.util.ViewUtils.runOnUiThread;

public class UserFragment extends BaseFragment<UserPresenter> implements UserContract.IUserView ,View.OnClickListener{
    private RecyclerView userRv;
    private View menuView,timeLineView;
    private UserAdapter userAdapter;
    private UserMenuAdapter menuAdapter;
    private RecyclerView menu_rv;
    private ImageView headImg;
    private TextView userName;
    private UserBroadCast userBroadCast;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        userBroadCast=new UserBroadCast();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(BroadAction.UPDATEUSERACTION);
        getActivity().registerReceiver(userBroadCast,intentFilter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(userBroadCast);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int bindLayout() {
        return R.layout.fragment_user;
    }

    @Override
    public void initView() {
        userRv = f(R.id.user_rv);
        menuView= LayoutInflater.from(getContext()).inflate(R.layout.view_user_menu,null);
        userName = menuView.findViewById(R.id.user_name);
        timeLineView=LayoutInflater.from(getContext()).inflate(R.layout.view_user_speed,null);
        headImg=menuView.findViewById(R.id.menu_head_img);
        headImg.setOnClickListener(this::onClick);
        menu_rv=menuView.findViewById(R.id.menu_rv);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),4);
        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        menu_rv.setLayoutManager(gridLayoutManager);
        menuAdapter=new UserMenuAdapter();
        menu_rv.setAdapter(menuAdapter);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        userRv.setLayoutManager(manager);
        userAdapter =new UserAdapter();
        userAdapter.addHeaderView(menuView,0);
        userAdapter.addHeaderView(timeLineView,1);
        userRv.setAdapter(userAdapter);
        userRv.addItemDecoration(new PartingLine(getContext()));
        userAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (userAdapter.getData().get(position).isSelFlag()){
                    userAdapter.getData().get(position).setSelFlag(false);
                }else {
                    userAdapter.getData().get(position).setSelFlag(true);
                }
                userAdapter.notifyDataSetChanged();
            }
        });
        EventBus.getDefault().register(this);

        userAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.user_items_tv:
                        if (userAdapter.getData().get(position).name.equals("更多设置")){
                            Intent intent = new Intent(getActivity(), LogoutActivity.class);
                            startActivity(intent);
                        }else {
                            return;
                        }
                        break;
                }
            }
        });
    }

    @Subscribe(sticky = true,threadMode = ThreadMode.MAIN)
    public void getEven(String s){
        if (!s.isEmpty()){
            if (s.equals("退出登录")){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        headImg.setImageResource(R.mipmap.pn_placeholder);
                        userName.setText("登录/注册");
                    }
                });
            }else if (s.equals("刷新")){
                List<UserEntity> userEntities = UserManager.getInstance().getDaoSession().loadAll(UserEntity.class);
                LogUtils.json(userEntities);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (userEntities.get(0).getUser_img()!=null){
                            Glide.with(getActivity()).load(userEntities.get(0).getUser_img())
                                    .transform(new CenterCrop(), new CircleCrop()).into(headImg);
                        }else {
                            headImg.setImageResource(R.mipmap.pn_placeholder);
                        }
                        userName.setText(userEntities.get(0).user_name);
                    }
                });
            }

        }
    }



    @Override
    public void initData() {
        p.initData();
    }

    @Override
    public void inject() {
        DaggerUserComponent.builder().userModules(new UserModules(this)).build().inject(this);
    }

    @Override
    public void refresh(BaseEntity baseEntity) {

    }

    @Override
    public void refreshMenu(List<UserMenuEntity> menus) {
        menuAdapter.setNewData(menus);
    }

    @Override
    public void refreshItems(List<UserItemEntity> items) {
        userAdapter.setNewData(items);
    }

    @Override
    public void showUser(BaseEntity baseEntity) {
//        LogUtils.json(baseEntity);
        ResponseUserEntity responseUserEntity= (ResponseUserEntity) baseEntity;
        Glide.with(getActivity()).load(responseUserEntity.getValues().getUser_img())
                .transform(new CenterCrop(), new CircleCrop()).into(headImg);
    }

//    @Override
//    public int addBarColor() {
//        return Color.RED;
//    }
//
//    @Override
//    public View addStatusView() {
//        return f(R.id.user_linear);
//    }


    @Override
    public void onClick(View v) {
        if (SpUtils.getLogin()){
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            startActivityForResult(intent,100);
        }else {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        }
    }

    private void refreshUserData(UserEntity userEntity){
        userName.setText(userEntity.user_name);
        p.selUser(userEntity.user_id, HttpCode.SELUSERCODE);
//        Log.i("wxy", "refreshUserData: "+userEntity.user_id);
    }

    private class UserBroadCast extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BroadAction.UPDATEUSERACTION)){
                UserEntity userEntity=intent.getParcelableExtra("userValues");
                refreshUserData(userEntity);
            }
        }
    }
}

